package fr.efrei.tradesys.hibernate.daoImpl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import fr.efrei.tradesys.hibernate.HibernateUtil;
import fr.efrei.tradesys.hibernate.beans.AppUser;
import fr.efrei.tradesys.hibernate.beans.Currency;
import fr.efrei.tradesys.hibernate.beans.Owned;
import fr.efrei.tradesys.hibernate.dao.OwnedDao;

public class OwnedDaoImpl implements OwnedDao
{

	private static OwnedDaoImpl	instance	= new OwnedDaoImpl();

	public static OwnedDaoImpl getInstance()
	{
		return instance;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Owned> getAllOwned()
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(Owned.class);
		List<Owned> list = (List<Owned>) criteria.list();
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Owned getOwned(AppUser u, Currency c)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(Owned.class)
				.add(Restrictions.eq("appUser.login", u.getLogin()))
				.add(Restrictions.eq("currency.code", c.getCode()));
		List<Owned> list = (List<Owned>) criteria.list();
		if (list.size() > 0)
			return list.get(0);
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Owned> getOwned(AppUser u)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(Owned.class).add(
				Restrictions.eq("appUser.login", u.getLogin()));
		List<Owned> list = (List<Owned>) criteria.list();
		return list;
	}

	@Override
	public void addOwned(Owned o)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.saveOrUpdate(o);
	}

	@Override
	public void updateOwned(Owned o)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.saveOrUpdate(o);
	}

	@Override
	public void removeOwned(Owned o)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.delete(o);
	}

}
